/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { Button, Modal, Row, Radio, Col, Form, Input } from 'antd';
import React, { useState } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import styles from './index.less';

const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

const AreaAddModal = props => {
  const { form, submitting, dispatch } = props;
  const { getFieldDecorator, validateFields, resetFields } = form;
  const [visible, setVisible] = useState(false);
  const [radioValue, setRadioValue] = useState('code');
  const [captchaLoading, setCaptchaLoading] = useState(false);
  const [numCount, setNumCount] = useState();

  const openModal = () => setVisible(true);
  const onClose = () => setVisible(false);
  const handleSearch = event => {
    event.preventDefault();
    getFormValues(values => {
      dispatch({
        type: 'area/AddAreaPost',
        payload: {
          ...values,
          type: radioValue,
        },
        then: code => {
          if (!code) {
            resetFields();
            setVisible(false);
          }
        },
      });
    });
  };

  const getFormValues = then => {
    validateFields((err, fieldsValue) => {
      if (err) {
        if (
          radioValue == 'phone' &&
          Object.keys(err).some(item => ['phone', 'code'].includes(item))
        ) {
          return;
        }
        return;
      }
      const values = {
        ...fieldsValue,
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format('YYYY-MM-DD'));
        const [start, end] = values.date;
        values.start_at = start;
        values.end_at = end;
        delete values.date;
      }
      then(values);
    });
  };

  const onRadioChange = event => {
    setRadioValue(event.target.value);
  };

  const onGetCaptcha = () => {
    validateFields(['phone'], { force: true }, (err, values) => {
      if (!err) {
        setCaptchaLoading(true);
        dispatch({
          type: 'area/SendCode',
          payload: {
            ...values,
          },
          then: () => {
            let count = 59;
            setNumCount(count);
            clearInterval(window.interval);
            window.interval = setInterval(() => {
              count -= 1;
              setNumCount(count);
              if (count === 0) {
                clearInterval(window.interval);
              }
            }, 1000);
          },
        }).then(() => {
          setCaptchaLoading(false);
        });
      }
    });
  };

  const auth_code = (
    <div>
      <div className={styles.auth_input} style={{ paddingTop: '30px', height: '1px' }} />
      <FormItem>
        <Row gutter={8}>
          <Col span={16} push={4}>
            {getFieldDecorator('auth_code', {
              initialValue: '',
              rules: [
                {
                  required: radioValue === 'code',
                  message: '请输入授权码',
                },
              ],
            })(<Input placeholder="输入驿站的数据查看授权码" />)}
          </Col>
        </Row>
      </FormItem>
    </div>
  );

  const captcha = (
    <div>
      <div style={{ paddingTop: '30px' }} />
      <FormItem>
        <Row gutter={8}>
          <Col span={16} push={4}>
            {getFieldDecorator('phone', {
              initialValue: '',
              rules: [
                {
                  required: radioValue === 'phone',
                  message: '请输入手机号',
                },
              ],
            })(<Input placeholder="请输入该驿站的注册手机号" />)}
          </Col>
        </Row>
      </FormItem>
      <FormItem>
        <Row gutter={8}>
          <Col span={10} push={4}>
            {getFieldDecorator('code', {
              rules: [
                {
                  required: radioValue === 'phone',
                  message: '请输入验证码！',
                },
                {
                  min: 4,
                  message: '至少输入4位',
                },
                {
                  max: 8,
                  message: '最多输入8位',
                },
              ],
            })(<Input autoComplete="off" placeholder="输入验证码" />)}
          </Col>
          <Col span={4} push={4}>
            <Button
              loading={captchaLoading}
              disabled={captchaLoading || numCount}
              className={styles.getCaptcha}
              onClick={onGetCaptcha}
            >
              {numCount ? `${numCount} s` : '获取验证码'}
            </Button>
          </Col>
        </Row>
      </FormItem>
    </div>
  );

  return (
    <>
      <Button className={styles.search} type="primary" onClick={openModal}>
        添加新的下属驿站
      </Button>
      <Modal
        visible={visible}
        centered
        onCancel={onClose}
        destroyOnClose
        footer={[
          <Button
            type="primary"
            htmlType="submit"
            key="search"
            loading={submitting}
            onClick={handleSearch}
          >
            添加
          </Button>,
        ]}
      >
        <div>
          <Row gutter={8}>
            <Col span={17} push={4}>
              <RadioGroup onChange={onRadioChange} defaultValue={radioValue}>
                <RadioButton value="code">使用数据查看码添加</RadioButton>
                <RadioButton value="phone">使用手机验证码添加</RadioButton>
              </RadioGroup>
            </Col>
          </Row>
          <div className={styles.auth_form}>
            <Form onSubmit={handleSearch}>{radioValue == 'code' ? auth_code : captcha}</Form>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default connect(({ loading }) => ({
  submitting: loading.effects['area/AddAreaPost'],
}))(Form.create()(AreaAddModal));
